﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Utility;

namespace Quanly
{
    public partial class SuaNguoiDung : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(IsPostBack) return;
            LoadUser();
        }

        #region Methods

        private void LoadUser()
        {
            var id = Request.QueryString["userid"];
            hdfUserId.Value = id;
            List<int> rights = new List<int>();
            var user = WebProvider.Provider.User.GetUserById(int.Parse(id),out rights);
            if(user==null) return;
            txtFullName.Value = user.FullName;
            txtPhone.Value = user.Phone;
            txtEmail.Value = user.Email;
            txtExtra.Value = user.ExtraInfo;
            if (rights.Any())
            {
                chboxUserMng.Checked = rights.Any(o => o == Constant.MANAGER_USER);
                chboxBillMng.Checked = rights.Any(o => o == Constant.MANAGER_BILL);
                chboxBillTotalMng.Checked = rights.Any(o => o == Constant.MANAGER_BILLTOTAL);
            }
        }

        private MsgReturn UpdateUser()
        {
            var fullname = txtFullName.Value.Trim();
            var phone = txtPhone.Value.Trim();
            var email = txtEmail.Value.Trim();
            var extra = txtExtra.Value.Trim();
            List<int> rights = new List<int>();
            if (chboxUserMng.Checked) rights.Add(Constant.MANAGER_USER);
            if (chboxBillMng.Checked) rights.Add(Constant.MANAGER_BILL);
            if (chboxBillTotalMng.Checked) rights.Add(Constant.MANAGER_BILLTOTAL);
            var user = new QLBH_User
            {
                UserID = int.Parse(hdfUserId.Value),
                FullName = fullname,
                Phone = phone,
                Email = email,
                ExtraInfo = extra,
                Status = 1
            };
            return WebProvider.Provider.User.UpdateUser(user, rights);
        }

        private void NoticeMsg(string msg)
        {
            ClientScript.RegisterStartupScript(typeof(Page), "SymbolAlert", string.Format("<script type='text/javascript'>alert('{0}');</script>", msg));
        }

        #endregion

        #region Events
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var msgReturn = UpdateUser();
            NoticeMsg(msgReturn.Message);
        }

        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            var msgReturn = UpdateUser();
            if (msgReturn.IsSuccess)
            {
                Response.Redirect(Constant.UserMng_Path);
            }
            else
            {
                NoticeMsg(msgReturn.Message);
            }
        }

        #endregion
    }
}